package org.example.im.common.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import org.example.im.bean.protocol.Packet;
import org.example.im.common.serialize.SerializerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author dingrui
 * @since 2022/2/11
 * @description 编解码器
 */
@Component
public class PacketCodecHandler extends MessageToMessageCodec<ByteBuf, Packet> {

    private static PacketCodec packetCodec;

    @Autowired
    private SerializerFactory serializerFactory;

    public PacketCodecHandler() {
        packetCodec = new PacketCodec(new SerializerFactory());
    }

    @PostConstruct
    public void init() {
        packetCodec = new PacketCodec(this.serializerFactory);
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Packet packet, List<Object> list) throws Exception {
        ByteBuf byteBuf = channelHandlerContext.channel().alloc().ioBuffer();
        packetCodec.encode(packet, byteBuf);
        list.add(byteBuf);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        list.add(packetCodec.decode(byteBuf));
    }
}
